package system;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
/**
 * https://www.cnblogs.com/maokun/p/7629068.html
 */
public class MappedFileGc {
    public static void main(String[] args) throws IOException {

        File tempFile = File.createTempFile("Temp", null);
        /**
         *  当调用deleteOnExit()方法时，只是相当于对deleteOnExit（）作一个声明，当程序运行结束，
         *  JVM终止时才真正调用deleteOnExit()方法实现删除操作。即该方法是将删除的命令缓存了一下，到服务停止的时候再进行操作！
         */
        tempFile.deleteOnExit();
        //https://www.cnblogs.com/dongguacai/p/5699444.html
        RandomAccessFile raTempFile = new RandomAccessFile(tempFile, "rw");
        //https://www.cnblogs.com/kuoAT/p/7010056.html
        FileChannel fChannel = raTempFile.getChannel();

        MappedByteBuffer mappedBuffer = fChannel.map(
                FileChannel.MapMode.READ_WRITE, 0, 512);

        fChannel.close();
        raTempFile.close();
        mappedBuffer = null;

        System.gc();

        if (tempFile.delete())
            System.out.println("Successfully deleted: " + tempFile);
        else
            System.out.println("Unable to delete: " + tempFile);
    }
}
